package com.qianli.user.domain.respository;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.xjd.user.common.utils.MD5;
import com.fqgj.xjd.user.dao.*;
import com.fqgj.xjd.user.entity.*;
import com.fqgj.xjd.user.mapper.UserAuthDataHistoryMapper;
import com.fqgj.xjd.user.mapper.UserAuthDataMapper;
import com.fqgj.xjd.user.mapper.UserCreditCardBillMapper;
import com.google.common.collect.Lists;
import com.qianli.user.domain.enums.UserAuthStatusEnum;
import com.qianli.user.domain.enums.UserModelItemStatusEnum;
import com.qianli.user.domain.enums.ZmCreditStatusEnum;
import com.qianli.user.domain.model.UserAuthModel;
import com.qianli.user.domain.model.auth.*;
import com.qianli.user.enums.CreditAuthTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * name:认证
 * auth:ting.li@qianli-inc.com
 * date:2018/1/2 15:49
 * version: v1.0.0
 **/
@Repository
public class UserAuthRespository implements BaseRespository<UserAuthModel> {

    @Autowired
    private UserAccessDao userAccessDao;
    @Autowired
    private UserAuthZhimaDao userAuthZhimaDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserAuthXuexinDao userAuthXuexinDao;
    @Autowired
    private UserAuthFaceRecognitionDao userAuthFaceRecognitionDao;
    @Autowired
    private UserAuthFaceRecognitionDetailDao userAuthFaceRecognitionDetailDao;
    @Autowired
    private UserAuthFaceRecognitionHistoryDao userAuthFaceRecognitionHistoryDao;
    @Autowired
    private UserAuthCreditDao userAuthCreditDao;
    @Autowired
    private UserAuthBankDao userAuthBankDao;
    @Autowired
    private UserAuthDataMapper userAuthDataMapper;
    @Autowired
    private UserAuthDataHistoryMapper userAuthDataHistoryMapper;
    @Autowired
    private UserCreditCardBillMapper userCreditCardBillMapper;
    @Autowired
    private UserThirdPartDao userThirdPartDao;


    @Override
    public void load(UserAuthModel userAuthModel) {
        String userCode = userAuthModel.getUserCode();
        userAuthModel.setUserCode(userCode);
        //客户信息
        UserAccessEntity accessEntity = userAccessDao.selectUserAccessByUserCode(userAuthModel.getUserCode());
        UserEntity userEntity = userDao.selectByCustomerCode(accessEntity.getCustomerCode());
        if (null != userEntity) {
            Customer customer = new Customer();
            BeanUtils.copyProperties(userEntity, customer);
            customer.setAppCode(String.valueOf(userEntity.getAppCode()));
            customer.setUserCode(userCode);
            userAuthModel.setCustomer(customer);
        }
        //芝麻信息
        UserAuthZhimaEntity zhimaEntity = userAuthZhimaDao.selectUserAuthZhimaByUserCode(userCode);
        if (null != zhimaEntity) {
            ZhimaCredit zhimaCredit = new ZhimaCredit();
            BeanUtils.copyProperties(zhimaEntity, zhimaCredit);
            zhimaCredit.setUserName(zhimaEntity.getName());
            zhimaCredit.setAuthorized(zhimaEntity.getStatus() == ZmCreditStatusEnum.SUCCESS.getType() ? true : false);
            userAuthModel.setZmCredit(zhimaCredit);
        }
        //银行卡
        List<UserAuthBankEntity> bankEntities = userAuthBankDao.selectAllUserBankByUserCode(userCode);
        if (CollectionUtils.isNotEmpty(bankEntities)) {
            List<BankCredit> bankCredits = Lists.newArrayList();
            for (UserAuthBankEntity bankEntity : bankEntities) {
                BankCredit bc = new BankCredit();
                BeanUtils.copyProperties(bankEntity, bc);
                bc.setBankName(bankEntity.getName());
                bc.setBankCode(bankEntity.getCode());
                bc.setBindType(bankEntity.getType());
                bc.setDefaultCard(bankEntity.getIsDefault() == 1 ? true : false);
                bc.setNumber(bankEntity.getCardNo());
                bc.setBindSuccess(bc.getStatus() == 1);
                bc.setAuthorized(bc.getStatus() == 1);
                bankCredits.add(bc);
            }
            userAuthModel.setBankCredits(bankCredits);
        }
        //人脸识别
        List<UserAuthFaceRecognitionEntity> recognitionEntities = userAuthFaceRecognitionDao.selectUserAuthFaceRecognitionByUserCode(userCode);
        if (CollectionUtils.isNotEmpty(recognitionEntities)) {
            List<UserAuthFaceRecognition> ufrs = Lists.newArrayList();
            for (UserAuthFaceRecognitionEntity faceRecognitionEntity : recognitionEntities) {
                UserAuthFaceRecognition ufr = new UserAuthFaceRecognition();
                BeanUtils.copyProperties(faceRecognitionEntity, ufr);
                ufr.setAuthorized(ufr.getPassed() == 1);
                ufrs.add(ufr);
            }
            userAuthModel.setAuthFaceRecognitions(ufrs);
        }

        //支付宝认证、淘宝、Google、Facebook、Twitter认证
        List<UserAuthDataEntity> authDataEntities = userAuthDataMapper.selectByUserCode(userCode);

        UserAuthDataEntity alipayEntity = filterAuthData(authDataEntities, CreditAuthTypeEnum.ALIPAY.getType());
        UserAuthDataEntity authTaobaoEntity = filterAuthData(authDataEntities, CreditAuthTypeEnum.TAOBAO.getType());
        UserAuthDataEntity userGoogleEntity = filterAuthData(authDataEntities, CreditAuthTypeEnum.GOOGLE.getType());
        UserAuthDataEntity userFacebookEntity = filterAuthData(authDataEntities, CreditAuthTypeEnum.FACEBOOK.getType());
        UserAuthDataEntity userTwitterEntity = filterAuthData(authDataEntities, CreditAuthTypeEnum.TWITTER.getType());
        List<UserAuthDataEntity> creditCardEntities = filterCreditCardAuthData(authDataEntities, CreditAuthTypeEnum.CREDIT_CARD.getType());
        if (null != alipayEntity) {
            UserAuthAlipay authAlipay = JSON.parseObject(alipayEntity.getData(), UserAuthAlipay.class);
            authAlipay.setId(alipayEntity.getId());
            authAlipay.setAuthorized(UserAuthStatusEnum.AUTHORIZED.getStatus().equals(alipayEntity.getStatus()));
            userAuthModel.setAuthAlipay(authAlipay);
        }
        if (null != authTaobaoEntity) {
            UserAuthTaobao authTaobao = JSON.parseObject(authTaobaoEntity.getData(), UserAuthTaobao.class);
            authTaobao.setId(authTaobaoEntity.getId());
            authTaobao.setAuthorized(UserAuthStatusEnum.AUTHORIZED.getStatus().equals(authTaobaoEntity.getStatus()));
            userAuthModel.setAuthTaobao(authTaobao);
        }
        if (null != userFacebookEntity) {
            UserAuthFacebook authFacebook = JSON.parseObject(userFacebookEntity.getData(), UserAuthFacebook.class);
            authFacebook.setId(userFacebookEntity.getId());
            authFacebook.setAuthorized(UserAuthStatusEnum.AUTHORIZED.getStatus().equals(userFacebookEntity.getStatus()));
            authFacebook.setStatus(userFacebookEntity.getStatus());
            userAuthModel.setUserAuthFacebook(authFacebook);
        }
        if (null != userGoogleEntity) {
            UserAuthGoogle authGoogle = new UserAuthGoogle();
            authGoogle.setId(userGoogleEntity.getId());
            authGoogle.setAuthorized(UserAuthStatusEnum.AUTHORIZED.getStatus().equals(userGoogleEntity.getStatus()));
            authGoogle.setStatus(userGoogleEntity.getStatus());
            authGoogle.setDataUrl(userGoogleEntity.getData());
            userAuthModel.setUserAuthGoogle(authGoogle);
        }
        if (null != userTwitterEntity) {
            UserAuthTwitter authTwitter = new UserAuthTwitter();
            authTwitter.setId(userTwitterEntity.getId());
            authTwitter.setAuthorized(UserAuthStatusEnum.AUTHORIZED.getStatus().equals(userTwitterEntity.getStatus()));
            authTwitter.setStatus(userTwitterEntity.getStatus());
            authTwitter.setDataUrl(userTwitterEntity.getData());
            userAuthModel.setUserAuthTwitter(authTwitter);
        }
        if (CollectionUtils.isNotEmpty(creditCardEntities)) {
            List<CreditCard> creditCards = Lists.newArrayList();
            for (UserAuthDataEntity entity : creditCardEntities) {
                CreditCard creditCard = JSON.parseObject(entity.getData(), CreditCard.class);
                creditCard.setId(entity.getId());
                creditCard.setAuthorized(UserAuthStatusEnum.AUTHORIZED.getStatus().equals(entity.getStatus()));
                creditCards.add(creditCard);
            }
            List<UserCreditCardBillEntity> billEntities = userCreditCardBillMapper.selectAllLatestBill(userCode);
            for (CreditCard creditCard : creditCards) {
                for (UserCreditCardBillEntity billEntity : billEntities) {
                    if (creditCard.getBankKey().equals(billEntity.getBankKey())) {
                        CreditCardBill bill = new CreditCardBill();
                        BeanUtils.copyProperties(billEntity, bill);
                        creditCard.setBills(Lists.newArrayList(bill));
                    }
                }
            }
            userAuthModel.setCreditCards(creditCards);
        }
    }

    private List<UserAuthDataEntity> filterCreditCardAuthData(List<UserAuthDataEntity> authDataEntities, Integer type) {
        List<UserAuthDataEntity> entities = Lists.newArrayList();
        for (UserAuthDataEntity entity : authDataEntities) {
            if (type.equals(entity.getType())) {
                entities.add(entity);
            }
        }
        return entities;
    }

    /**
     * 按类型取认证数据
     *
     * @param authDataEntities
     * @param type
     * @return
     */
    private UserAuthDataEntity filterAuthData(List<UserAuthDataEntity> authDataEntities, Integer type) {

        for (UserAuthDataEntity entity : authDataEntities) {
            if (type.equals(entity.getType())) {
                return entity;
            }
        }
        return null;
    }

    public void store(UserAuthModel model) {
        //客户信息
        if (null != model.getCustomer()) {
            UserEntity entity = new UserEntity();
            BeanUtils.copyProperties(model.getCustomer(), entity);
            entity.setAppCode(String.valueOf(model.getCustomer().getAppCode()));
            entity.setMd5MobileIdentityNo(MD5.md5(entity.getMobile() + entity.getIdentityNo()));
            //更新实名
            if (UserModelItemStatusEnum.ADD.getType().equals(model.getCustomer().getItemStatus())) {
                userDao.insert(entity);
            }
            userAccessDao.updateCustomerCodeByUserCode(model.getUserCode(), entity.getCustomerCode());
        }
        //芝麻信息
        if (null != model.getZmCredit()) {
            ZhimaCredit zhimaCredit = model.getZmCredit();
            UserAuthZhimaEntity entity = new UserAuthZhimaEntity();
            BeanUtils.copyProperties(zhimaCredit, entity);
            entity.setName(zhimaCredit.getUserName());
            if (UserModelItemStatusEnum.ADD.getType().equals(zhimaCredit.getItemStatus())) {
                userAuthZhimaDao.deleteByUserCode(entity.getUserCode());
                userAuthZhimaDao.insert(entity);
            } else if (UserModelItemStatusEnum.UPDATE.getType().equals(zhimaCredit.getItemStatus())) {
                userAuthZhimaDao.updateByPrimaryKey(entity);
            } else {
                userAuthZhimaDao.deleteByPrimaryKey(entity.getId());
            }
        }

        //银行卡
        if (CollectionUtils.isNotEmpty(model.getBankCredits())) {
            BankCredit bankCredit = model.getBankCredits().get(0);
            UserAuthBankEntity entity = new UserAuthBankEntity();
            BeanUtils.copyProperties(bankCredit, entity);
            entity.setName(bankCredit.getBankName());
            entity.setCode(bankCredit.getBankCode());
            entity.setType(bankCredit.getBindType());
            entity.setCardNo(bankCredit.getNumber());
            entity.setIsDefault(bankCredit.getDefaultCard() ? 1 : 0);
            if (UserModelItemStatusEnum.ADD.getType().equals(bankCredit.getItemStatus())) {
                userAuthBankDao.insert(entity);
            } else if (UserModelItemStatusEnum.UPDATE.getType().equals(bankCredit.getItemStatus())) {
                userAuthBankDao.updateByPrimaryKey(entity);
            } else {
                userAuthBankDao.deleteByPrimaryKey(entity.getId());
            }
        }
        //人脸识别
        if (CollectionUtils.isNotEmpty(model.getAuthFaceRecognitions())) {
            UserAuthFaceRecognition authFaceRecognition = model.getAuthFaceRecognitions().get(0);
            //人脸识别
            UserAuthFaceRecognitionEntity faceRecognitionEntity = new UserAuthFaceRecognitionEntity();
            //人脸识别详情
            UserAuthFaceRecognitionDetailEntity detailEntity = new UserAuthFaceRecognitionDetailEntity();
            UserAuthFaceRecognitionHistoryEntity faceRecognitionHistoryEntity = new UserAuthFaceRecognitionHistoryEntity();
            BeanUtils.copyProperties(authFaceRecognition, faceRecognitionEntity);
            //详情
            if (null != authFaceRecognition.getDetail()) {
                BeanUtils.copyProperties(authFaceRecognition.getDetail(), detailEntity);
            }
            //失败历史
            if (null != authFaceRecognition.getFailHistory()) {
                BeanUtils.copyProperties(authFaceRecognition.getFailHistory(), faceRecognitionHistoryEntity);
            }
            if (UserModelItemStatusEnum.ADD.getType().equals(authFaceRecognition.getItemStatus())) {
                userAuthFaceRecognitionDao.insert(faceRecognitionEntity);
                userAuthFaceRecognitionDetailDao.insert(detailEntity);
            } else if (UserModelItemStatusEnum.UPDATE.getType().equals(authFaceRecognition.getItemStatus())) {
                userAuthFaceRecognitionDao.updateByPrimaryKey(faceRecognitionEntity);
                userAuthFaceRecognitionDetailDao.updateByPrimaryKey(detailEntity);
            } else {
                userAuthFaceRecognitionDao.deleteByPrimaryKey(faceRecognitionEntity.getId());
                userAuthFaceRecognitionDetailDao.deleteByPrimaryKey(detailEntity.getId());
                userAuthFaceRecognitionHistoryDao.insert(faceRecognitionHistoryEntity);
            }
        }
        //支付宝 、淘宝、信用卡认证
        UserAuthDataEntity authDataEntity = null;
        Integer itemStatus = null;
        UserAuthAlipay userAuthAlipay = model.getAuthAlipay();
        UserAuthTaobao userAuthTaobao = model.getAuthTaobao();
        UserAuthFacebook userAuthFacebook = model.getUserAuthFacebook();
        UserAuthGoogle userAuthGoogle = model.getUserAuthGoogle();
        UserAuthTwitter userAuthTwitter = model.getUserAuthTwitter();
        List<CreditCard> creditCards = model.getCreditCards();
        //支付宝
        if (null != userAuthAlipay) {
            authDataEntity = new UserAuthDataEntity();
            authDataEntity.setId(userAuthAlipay.getId());
            authDataEntity.setUserCode(userAuthAlipay.getUserCode());
            authDataEntity.setType(CreditAuthTypeEnum.ALIPAY.getType());
            authDataEntity.setStatus(userAuthAlipay.getStatus());
            authDataEntity.setData(JSON.toJSONString(userAuthAlipay));
            itemStatus = userAuthAlipay.getItemStatus();
        }
        //淘宝
        if (null != userAuthTaobao) {
            authDataEntity = new UserAuthDataEntity();
            authDataEntity.setId(userAuthTaobao.getId());
            authDataEntity.setUserCode(userAuthTaobao.getUserCode());
            authDataEntity.setType(CreditAuthTypeEnum.TAOBAO.getType());
            authDataEntity.setStatus(userAuthTaobao.getStatus());
            authDataEntity.setData(JSON.toJSONString(userAuthTaobao));
            itemStatus = userAuthTaobao.getItemStatus();
        }
        //Facebook
        if (null != userAuthFacebook) {
            authDataEntity = new UserAuthDataEntity();
            authDataEntity.setId(userAuthFacebook.getId());
            authDataEntity.setUserCode(model.getUserCode());
            authDataEntity.setType(CreditAuthTypeEnum.FACEBOOK.getType());
            authDataEntity.setStatus(userAuthFacebook.getStatus());
            authDataEntity.setData(JSON.toJSONString(userAuthFacebook));
            itemStatus = userAuthFacebook.getItemStatus();
        }
        //Google
        if (null != userAuthGoogle) {
            authDataEntity = new UserAuthDataEntity();
            authDataEntity.setId(userAuthGoogle.getId());
            authDataEntity.setUserCode(model.getUserCode());
            authDataEntity.setType(CreditAuthTypeEnum.GOOGLE.getType());
            authDataEntity.setStatus(userAuthGoogle.getStatus());
            authDataEntity.setData(userAuthGoogle.getDataUrl());
            itemStatus = userAuthGoogle.getItemStatus();
        }
        //Twitter
        if (null != userAuthTwitter) {
            authDataEntity = new UserAuthDataEntity();
            authDataEntity.setId(userAuthTwitter.getId());
            authDataEntity.setUserCode(model.getUserCode());
            authDataEntity.setType(CreditAuthTypeEnum.TWITTER.getType());
            authDataEntity.setStatus(userAuthTwitter.getStatus());
            authDataEntity.setData(userAuthTwitter.getDataUrl());
            itemStatus = userAuthTwitter.getItemStatus();
        }
        List<UserCreditCardBillEntity> billEntities = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(creditCards)) {
            CreditCard creditCard = creditCards.get(0);

            authDataEntity = new UserAuthDataEntity();
            authDataEntity.setId(creditCard.getId());
            authDataEntity.setUserCode(creditCard.getUserCode());
            authDataEntity.setType(CreditAuthTypeEnum.CREDIT_CARD.getType());
            authDataEntity.setStatus(creditCard.getStatus());
            if (CollectionUtils.isNotEmpty(creditCard.getBills())) {
                for (CreditCardBill bill : creditCard.getBills()) {
                    UserCreditCardBillEntity billEntity = new UserCreditCardBillEntity();
                    BeanUtils.copyProperties(bill, billEntity);
                    billEntities.add(billEntity);
                }
                creditCard.setBills(null);
            }

            authDataEntity.setData(JSON.toJSONString(creditCard));
            itemStatus = creditCard.getItemStatus();
        }
        if (null == authDataEntity) {
            return;
        }
        if (UserModelItemStatusEnum.ADD.getType().equals(itemStatus)) {
            userAuthDataMapper.insert(authDataEntity);
        } else if (UserModelItemStatusEnum.UPDATE.getType().equals(itemStatus)) {
            userAuthDataMapper.updateByPrimaryKey(authDataEntity);
        } else if (UserModelItemStatusEnum.UPDATE_AND_HISTORIZATION.getType().equals(itemStatus)) {
            UserAuthDataEntity oldAuthDataEntity = userAuthDataMapper.selectByPrimaryKey(authDataEntity.getId());
            UserAuthDataHistoryEntity historyEntity = new UserAuthDataHistoryEntity();
            BeanUtils.copyProperties(oldAuthDataEntity, historyEntity);
            historyEntity.setId(null);
            userAuthDataHistoryMapper.insert(historyEntity);
            userAuthDataMapper.updateByPrimaryKey(authDataEntity);
        }
        //信用卡账单
        if (CollectionUtils.isNotEmpty(billEntities)) {
            userCreditCardBillMapper.batchInsert(billEntities);
        }

    }

    @Override
    public void restore(UserAuthModel model) {

    }

    public Customer getCustomerByIdentityNo(String identityNo) {
        UserEntity entity = userDao.selectByIdentityNo(identityNo);
        if (null == entity) {
            return null;
        }
        Customer customer = new Customer();
        BeanUtils.copyProperties(entity, customer);
        customer.setAppCode(String.valueOf(entity.getAppCode()));
        return customer;
    }
}
